<template>
    <a-upload
        v-model:file-list="fileList"
        name="file"
        :headers="headers"
        :show-upload-list="props.showUploadList?false:true"
        action="/api/admin/common/upload"
        :before-upload="beforeUpload"
        :maxCount="1"
        @change="handleChange"
    >
        <div v-if="props.showText" class="linkBtn">{{ props.text || '上传附件' }}</div>
        <a-button v-else>
            <upload-outlined></upload-outlined>
            {{ props.text || '上传附件' }}
        </a-button>
    </a-upload>
</template>
<script lang="ts" setup>
import {ref, onMounted, watch} from 'vue';
import {UploadOutlined} from '@ant-design/icons-vue';
import {message} from 'ant-design-vue';

const props = defineProps(['text', 'value', 'isBanner', 'type', 'saveName', 'showUploadList','showText','text'])
import type {UploadChangeParam, UploadProps} from 'ant-design-vue';

const emits = defineEmits(['getImageUrl', 'removeImageUrl']);
watch(() => props.value, (newVal, oldVal) => {
    let configData = []
    newVal && newVal.map((item, index) => {
        configData.push({
            uid: index + 1 + '',
            name: item.name,
            status: 'done',
            response: 'Server Error 500', // custom error message to show
            url: item.file
        })
    })
    fileList.value = configData;
});
onMounted(() => {
    let configData = []
    props.value && props.value.map((item, index) => {
        configData.push({
            uid: index + 1 + '',
            name: item.name,
            status: 'done',
            response: 'Server Error 500', // custom error message to show
            url: item.file
        })
    })
    fileList.value = configData;
})
const headers = ref({
    token: localStorage.getItem('token')
})

function getBase64(img: Blob, callback: (base64Url: string) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
}

const fileList = ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');
const handleCallback = (info: any) => {
    if (info.file.status === 'done') {
        console.log('接口返回信息:', info.file.response);
    } else if (info.file.status === 'error') {
        console.log('上传失败:', info.file.error);
    }
}
const handleChange = (info: UploadChangeParam) => {
    console.log(info, 'info')
    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === "removed") {
        let configData = []
        info.fileList.map(item => {
            configData.push({
                file: item.url,
                name: item.name
            })
        })
        emits('removeImageUrl', configData);
    }
    if (info.file.status === 'done') {
        if (props.saveName) {
            emits('getImageUrl', {
                file: info.file.response.data,
                name: info.file.name
            });
        } else {
            emits('getImageUrl', info.file.response.data);
        }
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (base64Url: string) => {
            imageUrl.value = base64Url;
            loading.value = false;
        });
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};

const beforeUpload = (file: UploadProps['fileList'][number]) => {
    // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    // if (!isJpgOrPng) {
    //     message.error('You can only upload JPG file!');
    // }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isLt2M;
};
</script>
<style scoped lang="less">
.banner-uploader {
    width: 300px;
    height: 150px;
    margin-right: 12px;
}

.avatar-uploader {
    width: 108px;
    height: 108px;
    margin-right: 12px;
}

:deep(.ant-upload) {
    width: 100% !important;
    height: 100% !important;
}

.ant-upload-wrapper.ant-upload-picture-card-wrapper .ant-upload.ant-upload-select {
    width: 100% !important;
    height: 100% !important;
}

.avatar-uploader > .ant-upload-select-picture-card {
    width: 100%;
    height: 100%;
}

.ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
}
</style>
